#!/usr/bin/env python

__author__ = 'Emiliano Dalla Verde Marcozzi'
__version__ = '0.1'
__copyright__ = 'Licencia GPL v2'

from config import *

import subprocess, platform, os, time
import supay
import optparse

pid_directory = os.getcwd()
daemon = supay.Daemon(name='pysysmonitor', pid_dir=pid_directory)

class Notifier:
    """
    """
    def checknewalarms(self):
        """ open ~/.sxnetmonitor/newalarms and 
        """
        dist = platform.dist()[0]
        alerts = '/' + ALERTS_LOCALFOLDER + '/' + ALERTS_LOCALFILE

        if 'Ubuntu' in dist:
            fh = open(os.path.expanduser('~') + alerts)
            if fh:
                for line in fh.readlines():
                    if SENDNOTIFY_ENABLED == 1:
                        subprocess.call(('notify-send', '%s' % line))
                    if ESPEAK_ENABLED == 1:
                        subprocess.call(('espeak', '-ves', '-s 90', '%s' % line))
                fh.close()
                # make empty file
                fh.open(os.path.expanduser('~') + alerts, 'w')
                fh.close()
                


def run():
    daemon.start()
    while True:
        n = Notifier()
        n.checknewalarms()
        time.sleep(10)
    
def stop():
    daemon.stop()

def spawn():
    daemon.spawn_child()
    sleep(20)

def status():
    daemon.status()

def main():
    p = optparse.OptionParser()
    options, arguments = p.parse_args()
    
    if arguments[0] == 'start':
        run()

    if arguments[0] == 'stop':
        stop()

    if arguments[0] == 'spawn':
        spawn()
        
    if arguments[0] == 'status':
        status()

if __name__ == '__main__':
    main()        
